{% extends 'IcsocUIBundle::page.html.twig' %}
{% from 'IcsocUIBundle:Macro:grid.html.twig' import gridWidth,gridNav,gridConfig %}
{% from 'IcsocUIBundle:Macro:actions.html.twig' import timebutton,searchtime,searchForm,searchFormBtn,playSound %}
{% block stylesheet %}
    {{ parent() }}
    {% stylesheets
    '@datepicker_css'
    '@jqgird_css'
    '@gritter_css'
    '@jquery_ui_css'
    '@chosen_css'
    filter='cssrewrite' filter='uglifycss'
    %}
    <link rel="stylesheet" href="{{ asset_url }}" />
    {% endstylesheets %}
{% endblock %}

{% block content %}
    <form action="javascript:search()" method="post" id="searchForm">
        <div class="widget-container-col">
            <div class="widget-box">
                <div class="widget-body">
                    <div class="widget-main no-padding">
                        <table class="table table-bordered table-hover no-padding">
                            <tbody>
                            {{ timebutton() }}
                            {{ searchForm(options) }}
                            {{ searchtime(date.today.start, date.today.end) }}
                            {{ searchFormBtn() }}
                            {{ playSound() }}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </form>
    <table id="grid-table"></table>
    <div id="grid-pager"></div>
    <div>
        <button onclick="selectAll(1, true)" class="btn btn-primary btn-round align-middle btn-sm">{{ 'Select all'|trans }}</button>
        <button onclick="selectAll(2)" class="btn btn-primary btn-round align-middle btn-sm">{{ 'Select not all'|trans }}</button>
        <span>你已经选择<b id="selectNum">0</b>行</span>
    </div>
{% endblock %}
{% block footer %}
    {% javascripts
    '@datepicker_js'
    '@jqgird_js'
    '@jquery_ui_js'
    '@gritter_js'
    '@common_js'
    '@chosen_js'
    filter='uglifyjs'
    %}
    <script src="{{ asset_url }}"></script>
    {% endjavascripts %}
    <script type="text/javascript">
        var isSpecial = {{ isSpecial }};
        $(function () {
            $('#start_time').datetimepicker({locale:'zh-cn',format:'YYYY-MM-DD HH:mm:ss',widgetPositioning:{horizontal:'left'}});
            $('#end_time').datetimepicker({locale:'zh-cn',format:'YYYY-MM-DD HH:mm:ss',widgetPositioning:{horizontal:'left'}});
            $('.chosen-select').chosen({width: $(".col-sm-6").width()+'px', allow_single_deselect:true, no_results_text:'{{ 'Not found'|trans }}'});
            if (isSpecial == 1) {
                $('.forBaidu').hide();
            }
        });
        var isSelectAll = 3;
        var isSelectedIds = []; //用于非全选用；
        var isCancelSelect = [];
        var countRecord = 0;
        var isOrigin = {{ isOrigin }};
        Array.prototype.remove=function(dx){
            if (isNaN(dx) || dx > this.length) {
                return false;
            }
            for (var i= 0,n=0;i<this.length;i++) {
                if (this[i] != this[dx]) {
                    this[n++] = this[i]
                }
            }
            this.length-=1;
        }
        jQuery(function($) {
            {{ gridWidth() }}
            jQuery(grid_selector).jqGrid({
                caption: "满意度评价明细报表",
                url: "{{ path('icsoc_evaluate_detaillist') }}",
                postData: {param:jsonToString(getCondition())},
                records:true,
                colModel:[
                    {name:'actions' , index:'actions' , label: '{{ 'actions'|trans }}' , width:70 , sortable:false,formatter:function(value,cell,row){
                        return "<i class='fa fa-youtube-play voice_prover' onclick='listen(\""+row.call_id+"\")'></i>&nbsp;&nbsp;" +
                                "<i class='fa fa-download' onclick='downSound(\""+row.call_id+"\")'></i>";
                    }},
                    {name:'ag_num' , index:'ag_num' , label: '{{ 'Agent Num'|trans }}' , width:80 , sortable:false , frozen:true},
                    {name:'ag_name' , index:'ag_name' , label: '{{ 'Agent Name'|trans }}' , width:80 , sortable:false , frozen:true},
                    {% if isEnableGroup %}
                    {name:'group_id' , index:'group_id' , label: '{{ 'Business Group'|trans }}' , width:90 , sortable:false ,fixed:true},
                    {% endif %}
                    {name:'que_name' , index:'que_name' , label: '{{ 'Queue'|trans }}' , width:80 , sortable:false },
                    {name:'call_type' , index:'call_type' , label: '{{ 'Call type'|trans }}' , width:70 , sortable:false },
                    {name:'server_num' , index:'server_num' , label: '{{ 'Relay number'|trans }}' ,width:100, sortable:false },
                    {name:'ag_phone' , index:'ag_phone' , label: '{{ 'Agent Phone'|trans }}' ,width:100, sortable:false },
                    {name:'cus_phone' , index:'cus_phone' , label: '{{ 'The customer number'|trans }}' , width:140 , sortable:false },
                    {name:'start_time' , index:'start_time' , label: '{{ 'Start time'|trans }}' , width:140 , sortable:false },
                    {name:'end_time' , index:'end_time' , label: '{{ 'End time'|trans }}' , width:140 , sortable:false },
                    {name:'conn_secs' , index:'conn_secs' , label: '{{ 'The long recording time'|trans }}'  ,width:70 , sortable:false},
                    {% if isOrigin == 1 %}
                    {name:'evaluate' , index:'evaluate' , label: '{{ 'Evaluate Result'|trans }}'  ,width:60 , sortable:true },
                    {% for key, evaluate in evaluates %}
                    {name:'evaluate_{{ evaluate.id }}' , index:'evaluate_{{ evaluate.id }}' , label: '{{ evaluate.name }}' , width:80 , sortable:false },
                    {% endfor %}
                    {% else %}
                    {% if evaluateConfig is not empty %}
                    {% set index=0 %}
                    {% for key,evaluate in evaluateConfig %}
                    {% set index = index +1 %}
                    {name:'{{ evaluate.id }}', index:'{{ evaluate.id }}', label:'{{ "Evaluate Result"|trans }}'+{{ index }},width:100,sortable:false},
                    {% endfor %}
                    {% endif %}
                    {% endif %}
                    {name:'id' , index:'id' , label: '' ,hidden:true, width:80 , sortable:true , key:true}
                ],
                {{ gridConfig() }}
                sortname: 'id',
                multiselect:true,
                loadComplete: function(xhr) {
                    countRecord = xhr.records; //总记录数；
                    var table = this;
                    setTimeout(function(){
                        updatePagerIcons(table);
                    }, 0);
                    selectAll(isSelectAll);
                    {#$('.voice_prover').popover({#}
                    {#'html':true,#}
                    {#'trigger':'click',#}
                    {#'content':'<audio id="sound_player" class="align-middle" style="margin-top: 8px;color: white;width: 200px;" autoplay="autoplay" controls="controls" ' +#}
                    {#'src="">{{ 'Your browser does not support the player'|trans }}</audio>',#}
                    {#'placement':'right'#}
                    {#});#}
                },
                onSelectRow:function (rowId, status) {
                    //当取消选中 记录到变量中；
                    processData(rowId, status);
                    if (isSelectAll == 1) {
                        $("#selectNum").text(countRecord - isCancelSelect.length);
                    } else {
                        $("#selectNum").text(isSelectedIds.length);
                    }
                },
                onSelectAll:function (aRowids, status) {
                    for (var i=0; i < aRowids.length; i++) {
                        var rowId = aRowids[i];
                        processData(rowId, status);
                    }
                    if (isSelectAll == 1) {
                        $("#selectNum").text(countRecord - isCancelSelect.length);
                    } else {
                        $("#selectNum").text(isSelectedIds.length);
                    }
                },
                pginput:false
            });
            {{ gridNav(false,false,false,false,true,false) }}
            jQuery(grid_selector).navButtonAdd(
                    pager_selector,
                    {
                        caption:'{{ 'Export Csv'|trans }}',
                        buttonicon:'ace-icon fa fa-file-excel-o  primary',
                        onClickButton:function() {
                            location.href = "{{ path('icsoc_evaluate_detaillist', {'export': 'csv'})|raw }}&param="+jsonToString(getCondition());
                        }
                    }
            ).navButtonAdd(
                    pager_selector,
                    {
                        caption:'{{ 'Export Excel'|trans }}',
                        buttonicon:'ace-icon fa fa-file-excel-o  primary',
                        onClickButton:function() {
                            location.href = "{{ path('icsoc_evaluate_detaillist', {'export': 'excel'})|raw }}&param="+jsonToString(getCondition());
                        }
                    }
            );
        });

        $(document).ready(function(){
            $('#last_grid-pager').hide();
            $('#forAgent-ag_num').chosen({
                no_results_text:"{{ 'Not found'|trans }}",
                allow_single_deselect: true,
            });
            $.ajax({
                url: "{{ path('icsoc_report_getAgents') }}",
                type: 'post',
                data: {agentChosenSelect:'chosenSelect'},
                success: function (response) {
                    $('#forAgent-ag_num').append(response);
                    $("#forAgent-ag_num").trigger("chosen:updated");
                }
            });
            $('.normal-select').next().find('.chosen-search').hide();
            $('.evaluates').chosen({
                no_results_text:"{{ 'Not found'|trans }}",
            });
            $('.evaluates').next().find('.chosen-drop').find('.chosen-search').hide();

            $('.evaluates').chosen().change(function() {
                if ($(this).val() == -3 || $(this).val() == -1 || $(this).val() == -4) {
                    $('.evaluates-custom').prop('disabled', true).trigger("chosen:updated");
                } else {
                    $('.evaluates-custom').prop('disabled', false).trigger("chosen:updated");
                }
            });
        });

        /**
         * 重置
         */
        function resetBtn()
        {
            $('#searchForm')[0].reset();
            $(".chosen-select").trigger("chosen:updated");
            search();
        }

        /**
         * 搜索
         */
        function search()
        {
            $('#grid-table').setGridParam({page:1,postData:{param:jsonToString(getCondition())}}).trigger("reloadGrid");
        }

        /**
         * 获取搜索条件
         */
        function getCondition()
        {
            var $start_time = $('#start_time');
            var $end_time = $('#end_time');

            if (!$start_time.val()) {
                $start_time.parent().parent().addClass('has-error');
                $start_time.focus();
                return;
            }

            if (!$end_time.val()) {
                $end_time.parent().parent().addClass('has-error');
                $end_time.focus();
                return;
            }

            var param = {};

            if (isOrigin == 1) {
                var evaluates = $.trim($('#evaluates').val());
                if (evaluates != -5) {
                    evaluates.length >= 1 ?  param.evaluates = evaluates : '';
                }
            } else {
                var evaluate = [];
                $('.evaluates').each(function() {
                    var val = $(this).val();
                    if (val != -5) {
                        evaluate.push(val);
                    }
                });
                if (evaluate.length >=1) {
                    param.evaluates = evaluate;
                }
            }
            param.isOrigin = isOrigin;
            param.ag_num = $.trim($('#forAgent-ag_num').val());
            param.call_type = $('#call_type').val();
            param.ag_phone =  $.trim($('#ag_phone').val());
            param.cus_phone =  $.trim($('#cus_phone').val());
            param.que_id = $('#que_id').val();
            param.start_time =  $.trim($('#start_time').val());
            param.end_time =  $.trim($('#end_time').val());
            param.serv_num = $.trim($('#serv_num').val());
            // param.end_result =  $.trim($('#end_result').val());
            param.ssecs =  $.trim($('#ssecs').val());
            param.esecs =  $.trim($('#esecs').val());
            {% if isEnableGroup %}
            param.group_id = $('#group_id').val();
            {% endif %}
            return param;
        }

        /**
         * 设置时间
         *
         * @param type
         */
        function fnSetTime(type)
        {
            var $start_time = $('#start_time');
            var $end_time = $('#end_time');

            switch (type) {
                case 1:
                    $start_time.val('{{ date.yestoday.start }}');
                    $end_time.val('{{ date.yestoday.end }}');
                    break;
                case 2:
                    $start_time.val('{{ date.today.start }}');
                    $end_time.val('{{ date.today.end }}');
                    break;
                case 3:
                    $start_time.val('{{ date.lastweek.start }}');
                    $end_time.val('{{ date.lastweek.end }}');
                    break;
                case 4:
                    $start_time.val('{{ date.thisweek.start }}');
                    $end_time.val('{{ date.thisweek.end }}');
                    break;
                case 5:
                    $start_time.val('{{ date.lastmonth.start }}');
                    $end_time.val('{{ date.lastmonth.end }}');
                    break;
                case 6:
                    $start_time.val('{{ date.thismonth.start }}');
                    $end_time.val('{{ date.thismonth.end }}');
                    break;
                case 7:
                    $start_time.val('{{ date.thisyear.start }}');
                    $end_time.val('{{ date.thisyear.end }}');
                    break;
                case 8:
                    $start_time.val('{{ date.lastyear.start }}');
                    $end_time.val('{{ date.lastyear.end }}');
                    break;
            }

            search();
        }

        function listen(id)
        {
            /*
             if (countRecord == 1) {
             $('#grid-table').setRowData(id,false,{height:60});
             }
             $('.voice_prover').each(function(){
             obj != this ? $(this).popover('hide') : '';
             });
             $(this).on('hidden.bs.popover', function(){
             $(this).popover('show');
             });
             $('.voice_prover').on('shown.bs.popover',function(){
             var url = "{{ path('icsoc_recording_list_play_voice') }}?flag=2&id="+id;
         $('#sound_player').attr("src", url);
         });*/
            $.ajax({
                type:"get",
                url: '{{ path('icsoc_recording_list_play_voice') }}',
                data: {flag:2, callid: id},
                success: function(res){
                    if (res.err) {
                        gritterAlert('{{ 'Prompt'|trans }}','{{ 'File not exist'|trans }}', 'error');
                    } else {
                        $('#sound_player').attr("src", res.url);
                    }
                }
            });
        }
        function downSound(id)
        {
            $.ajax({
                type:"get",
                url: '{{ path('icsoc_recording_list_play_voice') }}',
                data: {flag:2, callid: id},
                success: function(res){
                    if (res.err) {
                        gritterAlert('{{ 'Prompt'|trans }}','{{ 'File not exist'|trans }}', 'error');
                    } else {
                        window.open(res.url);
                    }
                }
            });
        }
        function selectAll(flag, v)
        {
            //如果是点击按钮来的就清空；
            if (v) {
                isCancelSelect = [];
                isSelectedIds = [];
                $('#selectNum').text(countRecord);
            }
            isSelectAll = flag;
            var grid = $('#grid-table');
            if (flag == 1) {
                //全选
                grid.jqGrid('resetSelection');
                var ids = grid.getDataIDs();
                if (ids.length == 0 && countRecord == 0) {
                    isCancelSelect = [];
                    isSelectedIds = [];
                    $('#selectNum').text(countRecord); //如果记录为空；置零；
                    return ;
                }
                for (var i=0, il=ids.length; i < il; i++) {
                    if (isCancelSelect.indexOf(ids[i]) == -1) {
                        grid.jqGrid('setSelection',ids[i], true);
                    }
                }
            } else if (flag == 3) {
                //普通点击全选
                if (countRecord == 0) {
                    isCancelSelect = [];
                    isSelectedIds = [];
                    $('#selectNum').text(countRecord); //如果记录为空；置零
                    return ;
                }
                for (var i=0, il=isSelectedIds.length; i < il; i++) {
                    grid.jqGrid('setSelection',isSelectedIds[i], true);
                }
            } else {
                isCancelSelect = [];
                isSelectedIds = [];
                isSelectAll = 3;//重置成3
                $('#selectNum').text(0);
                grid.jqGrid('resetSelection');
            }
        }

        function processData(rowId, status)
        {
            if (!status && isCancelSelect.indexOf(rowId) == -1) {
                isCancelSelect.push(rowId);
            } else if (status && isCancelSelect.indexOf(rowId) != -1) {
                //如果又选中了就要从isCancelSelect中去掉
                var index = isCancelSelect.indexOf(rowId);
                isCancelSelect.remove(index);
            }
            if (status && isSelectAll == 3 && isSelectedIds.indexOf(rowId) == -1) {
                isSelectedIds.push(rowId);
            } else if (isSelectAll == 3 && !status) {
                var index = isSelectedIds.indexOf(rowId);
                isSelectedIds.remove(index);
            }
        }

        /**
         * 批量下载
         * @returns {boolean}
         */
        function batchDownload()
        {
            if ((isSelectedIds.length < 1 && isSelectAll==3) || countRecord <=0 ) {
                gritterAlert('{{ 'Prompt'|trans }}','{{ 'Please check the data'|trans }}', 'error');
                return ;
            }
            var search =$('#grid-table').jqGrid('getGridParam');
            var postData = '';
            if (isSelectAll==1) {
                //区分按钮；//获取grid 的搜索条件；
                postData = typeof(search.postData.param) != 'undefined' ? search.postData.param : '';
                //如果是全选；就得限制时间范围；
                var data = stringToJSON(postData);
                var start_time = data.start_time;
                var end_time = data.end_time;
                start_time = datetime_to_int(start_time);
                end_time = datetime_to_int(end_time);
                if ((end_time - start_time)/(3600*24) > 1) {
                    gritterAlert('{{ 'Prompt'|trans }}','{{ 'One day data only download'|trans }}', 'error');
                    return false;
                }
            }
            var isAll = isSelectAll == 1 ? 1 : 0;
            location.href="{{ path('icsoc_recording_list_batch_down_data') }}?filter="+postData+'&ids='+isSelectedIds+'&isall='+isAll+'&iscancelIds='+isCancelSelect;
        }
    </script>
{% endblock %}